package com.sheep.jucdemo.part7.part7_1;

import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @Date 2022/5/9 22:17
 * @Created by sheep
 */
public class Test7_1_3 {

    // add与offer两者都是往队列尾部插入元素，
    // 不同的时候，当超出队列界限的时候，add()方法是抛出异常让你处理，而offer()方法是直接返回false

    // poll：将首个元素从队列中弹出，如果队列是空的，就返回null
    // peek：查看首个元素，不会移除首个元素，如果队列是空的就返回null
    // element：查看首个元素，不会移除首个元素，如果队列是空的就抛出异常NoSuchElementException

    public static void main(String[] args) throws InterruptedException {
        ConcurrentLinkedQueue<Task> concurrentLinkedQueue = new ConcurrentLinkedQueue<Task>();
        Thread threadOne = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    Task task = new Task("线程：立即冻手-" + Thread.currentThread().getName() + "-" + System.currentTimeMillis());
                    concurrentLinkedQueue.add(task);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        Thread threadTwo = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    Task poll = concurrentLinkedQueue.poll();
                    if (null != poll){
                        poll.sedMessage();
                    }else {
                        System.out.println("当前队列为空");
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
        threadOne.start();
        threadTwo.start();
    }

    static class Task{
        private String message;

        public Task(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public void sedMessage() {
            System.out.println("发送消息：" + this.message);
        }
    }
}
